package com.zhou.common.pub.validator;

import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import javax.validation.constraints.NotNull;
import java.lang.annotation.*;
import java.util.Arrays;
import java.util.stream.Collectors;

import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

/**
 * @author 18576666986
 * @description
 * @createDate 2023/4/20 16:00
 */
@Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE})
@Retention(RetentionPolicy.RUNTIME)
@Repeatable(ValueInList.List.class)
@Constraint(validatedBy = ValueInList.Validator.class)
public @interface ValueInList {

    String message() default "{custom.value.invalid}";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    int[] values();

    /**
     * Defines several {@link NotNull} annotations on the same element.
     *
     * @see NotNull
     */
    @Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE})
    @Retention(RUNTIME)
    @Documented
    @interface List {

        ValueInList[] value();
    }

    class Validator implements ConstraintValidator<ValueInList, Integer> {

        private java.util.List<Integer> values;

        @Override
        public void initialize(ValueInList enumValue) {
            values = Arrays.stream(enumValue.values()).boxed().collect(Collectors.toList());
        }

        @Override
        public boolean isValid(Integer value, ConstraintValidatorContext constraintValidatorContext) {
            if (value == null) {
                return Boolean.TRUE;
            }
            if (values == null || values.size() == 0) {
                return Boolean.TRUE;
            }

            if (values.contains(value)) {
                return true;
            }
            return false;
        }

    }
}
